import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:get/get.dart' hide MultipartFile hide FormData;
import 'package:video_compress/video_compress.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:yp/Xwidgets/cache_image.dart';
import 'package:yp/helper.dart';
import 'package:yp/services/api.dart';

import 'logic.dart';
import 'state.dart';

class PingJiaShaiDanPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _PingJiaShaiDanPage();
  }
}

class _PingJiaShaiDanPage extends State<PingJiaShaiDanPage> {
  final PingJiaShaiDanLogic logic = Get.put(PingJiaShaiDanLogic());
  final PingJiaShaiDanState state = Get.find<PingJiaShaiDanLogic>().state;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        elevation: 0,
        backgroundColor: Colors.white,
        title: Text(
          '评价晒单',
          style: TextStyle(
            color: Color(0xff030303),
            fontSize: 17,
          ),
        ),
        iconTheme: IconThemeData(
          color: Color(0xff030303),
        ),
        actions: [
          GestureDetector(
            onTap: () {
              logic.submitComments(context: context);
            },
            behavior: HitTestBehavior.opaque,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: setWidth(20)),
              alignment: Alignment.center,
              child: Text(
                '提交',
                style: TextStyle(
                  color: Color(0xffEA5504),
                  fontSize: 15,
                ),
              ),
            ),
          ),
        ],
      ),
      body: GetBuilder<PingJiaShaiDanLogic>(
        builder: (logic) {
          return Container(
            color: Color(0xffF5F5F5),
            child: ListView.separated(
              scrollDirection: Axis.vertical,
              padding: EdgeInsets.only(
                bottom: setWidth(20),
              ),
              itemBuilder: (context, index) {
                return _commentGoodsWidget(index: index);
              },
              separatorBuilder: (BuildContext context, int index) {
                return SizedBox(
                  height: setWidth(20),
                );
              },
              itemCount: state.commentsList?.length ?? 0,
            ),
          );
        },
      ),
    );
  }

  // 评价商品
  Widget _commentGoodsWidget({
    int index,
  }) {
    List<AssetEntity> imageList = state.commentsList[index]['image'];
    List list = List.from(imageList);
    if (imageList.length < 9) {
      list.add('');
    }

    return Container(
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.only(
              left: setWidth(22),
              top: setWidth(20),
              right: setWidth(22),
              bottom: setWidth(36),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                CachedImage(
                  width: setWidth(100),
                  height: setWidth(100),
                  margin: EdgeInsets.zero,
                  scale: BoxFit.fill,
                  path: state.orderGoodsList[index]['item_picture'],
                ),
                SizedBox(
                  width: setWidth(18),
                ),
                Expanded(
                  child: Container(
                    height: setWidth(100),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          state.orderGoodsList[index]['item_name'],
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: Color(0xff222222),
                            fontSize: 14,
                          ),
                        ),
                        Row(
                          children: [
                            Wrap(
                              spacing: setWidth(20),
                              children: ['', '', '', '', '']
                                  .asMap()
                                  .map((key, value) {
                                    int goodsInt =
                                        state.commentsList[index]['goodsInt'];
                                    return MapEntry(
                                      key,
                                      InkWell(
                                        onTap: () {
                                          print('星星点击事件！！！');
                                          setState(() {
                                            state.commentsList[index]
                                                ['goodsInt'] = key + 1;
                                          });
                                        },
                                        child: Container(
                                          width: setWidth(52),
                                          height: setWidth(52),
                                          alignment: Alignment.center,
                                          child: goodsInt > key
                                              ? Image.asset(
                                                  'assets/images/fivePointedStar_image.png',
                                                  width: setWidth(50),
                                                  height: setWidth(50),
                                                  fit: BoxFit.fill,
                                                )
                                              : Image.asset(
                                                  'assets/images/fivePointedStarGray_image.png',
                                                  width: setWidth(50),
                                                  height: setWidth(50),
                                                  fit: BoxFit.fill,
                                                ),
                                        ),
                                      ),
                                    );
                                  })
                                  .values
                                  .toList(),
                            ),
                            SizedBox(
                              width: setWidth(20),
                            ),
                            Text(
                              state.commentsList[index]['goodsInt'] < 3
                                  ? '差评'
                                  : state.commentsList[index]['goodsInt'] < 5
                                      ? '中评'
                                      : '好评',
                              style: TextStyle(
                                color: Color(0xffEA5504),
                                fontSize: 14,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          Divider(
            height: setWidth(1),
            indent: setWidth(22),
            endIndent: 0,
          ),
          Padding(
            padding: EdgeInsets.symmetric(vertical: setWidth(18)),
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: setWidth(22)),
              child: TextField(
                controller: state.commentsList[index]['controller'],
                style: TextStyle(
                  color: Color(0xff222222),
                  fontSize: 12,
                ),
                maxLines: 5,
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.zero,
                  hintText: '针对本品发表一下您的看法和建议吧',
                  hintStyle: TextStyle(
                    color: Color(0xffcccccc),
                    fontSize: 12,
                  ),
                  enabledBorder: OutlineInputBorder(
                    // 设置输入框可编辑时的边框样式
                    borderRadius:
                        BorderRadius.all(Radius.circular(0)), // 设置边框四个角的弧度
                    borderSide: BorderSide(
                      // 用来配置边框的样式
                      color: Colors.transparent, // 设置边框的颜色
                      width: setWidth(1), // 设置边框的粗细
                    ),
                  ),
                  focusedBorder: OutlineInputBorder(
                    // 用来配置输入框获取焦点时的颜色
                    borderRadius:
                        BorderRadius.all(Radius.circular(0)), // 设置边框四个角的弧度
                    borderSide: BorderSide(
                      // 用来配置边框的样式
                      color: Colors.transparent, // 设置边框的颜色
                      width: setWidth(1), // 设置边框的粗细
                    ),
                  ),
                ),
              ),
            ),
          ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: setWidth(22)),
            child: Wrap(
              spacing: setWidth(24),
              runSpacing: setWidth(20),
              children: list
                  .asMap()
                  .map((key, value) {
                    if (imageList.length > key) {
                      var asset = imageList[key];
                      return MapEntry(
                        key,
                        Container(
                          width: setWidth(120),
                          height: setWidth(120),
                          // 展示图片
                          child: RepaintBoundary(
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(8.0),
                              child: Stack(
                                children: [
                                  /*  asset.type == AssetType.video
                                      ? Container(
                                          color: Colors.grey,
                                        )
                                      :*/
                                  Image(
                                    image: AssetEntityImageProvider(
                                        imageList[key],
                                        isOriginal: false),
                                    width: setWidth(120),
                                    height: setWidth(120),
                                    fit: BoxFit.cover,
                                  ),
                                  Visibility(
                                    visible: asset.type == AssetType.video,
                                    child: Positioned(
                                      left: setWidth(30),
                                      top: setWidth(30),
                                      child: Icon(
                                        Icons.play_circle,
                                        size: setWidth(60),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              // child: AssetWidgetBuilder(
                              //   entity: asset,
                              //   isDisplayingDetail: value,
                              // ),
                            ),
                          ),
                          // child: AssetThumb(
                          //   asset: imageList[key],
                          //   width: setWidth(120) ~/ 1,
                          //   height: setWidth(120) ~/ 1,
                          // ),
                        ),
                      );
                    }
                    return MapEntry(
                      key,
                      InkWell(
                        onTap: () {
                          print('！！！选择照片点击事件！！！   index = $index');
                          // loadAssets(
                          //   index: index,
                          //   imagesAssetList: imageList,
                          // );
                          chooseSource(
                            index: index,
                            imagesAssetList: imageList,
                          );
                        },
                        child: Container(
                          width: setWidth(120),
                          height: setWidth(120),
                          alignment: Alignment.center,
                          child: Image.asset(
                            'assets/images/takingPictures_image.png',
                            width: setWidth(120),
                            height: setWidth(120),
                            fit: BoxFit.fill,
                          ),
                        ),
                      ),
                    );
                  })
                  .values
                  .toList(),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 15, left: 10),
            child: Container(
              child: Column(
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text(
                        '物流服务',
                        style: TextStyle(
                          color: Color(0xff666666),
                          fontSize: 14,
                        ),
                      ),
                      SizedBox(
                        width: setWidth(20),
                      ),
                      Wrap(
                        spacing: setWidth(20),
                        children: ['', '', '', '', '']
                            .asMap()
                            .map((key, value) {
                              int goodsInt = state.commentsList[index]
                                  ['logisticsServiceInt'];
                              return MapEntry(
                                key,
                                InkWell(
                                  onTap: () {
                                    setState(() {
                                      state.commentsList[index]
                                          ['logisticsServiceInt'] = key + 1;
                                    });
                                  },
                                  child: Container(
                                    width: setWidth(52),
                                    height: setWidth(52),
                                    alignment: Alignment.center,
                                    child: goodsInt > key
                                        ? Image.asset(
                                            'assets/images/fivePointedStar_image.png',
                                            width: setWidth(50),
                                            height: setWidth(50),
                                            fit: BoxFit.fill,
                                          )
                                        : Image.asset(
                                            'assets/images/fivePointedStarGray_image.png',
                                            width: setWidth(50),
                                            height: setWidth(50),
                                            fit: BoxFit.fill,
                                          ),
                                  ),
                                ),
                              );
                            })
                            .values
                            .toList(),
                      ),
                      SizedBox(
                        width: setWidth(20),
                      ),
                      Text(
                        state.commentsList[index]['logisticsServiceInt'] < 3
                            ? '差评'
                            : state.commentsList[index]['logisticsServiceInt'] <
                                    5
                                ? '中评'
                                : '好评',
                        style: TextStyle(
                          color: Color(0xffEA5504),
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 10),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Text(
                          '服务态度',
                          style: TextStyle(
                            color: Color(0xff666666),
                            fontSize: 14,
                          ),
                        ),
                        SizedBox(
                          width: setWidth(20),
                        ),
                        Wrap(
                          spacing: setWidth(20),
                          children: ['', '', '', '', '']
                              .asMap()
                              .map((key, value) {
                                int goodsInt = state.commentsList[index]
                                    ['serviceAttitudeInt'];
                                return MapEntry(
                                  key,
                                  InkWell(
                                    onTap: () {
                                      setState(() {
                                        state.commentsList[index]
                                            ['serviceAttitudeInt'] = key + 1;
                                      });
                                    },
                                    child: Container(
                                      width: setWidth(52),
                                      height: setWidth(52),
                                      alignment: Alignment.center,
                                      child: goodsInt > key
                                          ? Image.asset(
                                              'assets/images/fivePointedStar_image.png',
                                              width: setWidth(50),
                                              height: setWidth(50),
                                              fit: BoxFit.fill,
                                            )
                                          : Image.asset(
                                              'assets/images/fivePointedStarGray_image.png',
                                              width: setWidth(50),
                                              height: setWidth(50),
                                              fit: BoxFit.fill,
                                            ),
                                    ),
                                  ),
                                );
                              })
                              .values
                              .toList(),
                        ),
                        SizedBox(
                          width: setWidth(20),
                        ),
                        Text(
                          state.commentsList[index]['serviceAttitudeInt'] < 3
                              ? '差评'
                              : state.commentsList[index]
                                          ['serviceAttitudeInt'] <
                                      5
                                  ? '中评'
                                  : '好评',
                          style: TextStyle(
                            color: Color(0xffEA5504),
                            fontSize: 14,
                          ),
                        ),
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
          SizedBox(
            height: setWidth(16),
          ),
          Divider(
            height: setWidth(1),
            indent: setWidth(22),
            endIndent: 0,
          ),
          Container(
            // height: setWidth(68),
            padding: EdgeInsets.symmetric(horizontal: setWidth(22)),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                InkWell(
                  onTap: () {
                    setState(() {
                      state.commentsList[index]['whetherAnonymous'] =
                          !state.commentsList[index]['whetherAnonymous'];
                    });
                  },
                  child: Container(
                    alignment: Alignment.centerLeft,
                    padding: EdgeInsets.only(
                      top: setWidth(22),
                      right: setWidth(22),
                      bottom: setWidth(22),
                    ),
                    child: Image.asset(
                      state.commentsList[index]['whetherAnonymous']
                          ? 'assets/images/selectIcon1.png'
                          : 'assets/images/save.png',
                      width: setWidth(34),
                      height: setWidth(34),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                // SizedBox(
                //   width: setWidth(16),
                // ),
                Text(
                  '匿名评价',
                  style: TextStyle(
                    color: Color(0xff333333),
                    fontSize: 12,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  chooseSource({
    int index,
    List<AssetEntity> imagesAssetList,
  }) {
    showModalBottomSheet(
      isScrollControlled: true,
      builder: (BuildContext context) {
        //构建弹框中的内容
        return Container(
          color: Colors.white,
          height: setWidth(330) + Get.bottomBarHeight,
          margin: EdgeInsets.only(bottom: Get.bottomBarHeight),
          child: Column(
            children: [
              Column(
                children: [
                  InkWell(
                    onTap: () {
                      Get.back();
                      choosePhoto(
                        index: index,
                        imagesAssetList: imagesAssetList,
                        sourceType: RequestType.image,
                      );
                    },
                    child: Container(
                      height: setWidth(100),
                      alignment: Alignment.center,
                      child: Text(
                        "照片",
                        style: TextStyle(
                          color: Color(0xff222222),
                          fontSize: setWidth(32),
                        ),
                      ),
                    ),
                  ),
                  Divider(
                    height: 1,
                    color: Color(0xffeeeeee),
                  ),
                  InkWell(
                    onTap: () {
                      Get.back();
                      choosePhoto(
                        index: index,
                        imagesAssetList: imagesAssetList,
                        sourceType: RequestType.video,
                      );
                    },
                    child: Container(
                      height: setWidth(100),
                      alignment: Alignment.center,
                      child: Text(
                        "视频",
                        style: TextStyle(
                          color: Color(0xff222222),
                          fontSize: setWidth(32),
                        ),
                      ),
                    ),
                  ),
                  Divider(
                    height: 1,
                    color: Color(0xffeeeeee),
                  ),
                  InkWell(
                    onTap: () {
                      Get.back();
                    },
                    child: Container(
                      height: setWidth(100),
                      alignment: Alignment.center,
                      child: Text(
                        "取消",
                        style: TextStyle(
                          color: Color(0xff222222),
                          fontSize: setWidth(32),
                        ),
                      ),
                    ),
                  ),
                ],
              )
            ],
          ),
        );
      },
      context: context,
    );
  }

  Future<void> choosePhoto({
    int index,
    List<AssetEntity> imagesAssetList,
    RequestType sourceType = RequestType.image,
  }) async {
    List<AssetEntity> asset = await AssetPicker.pickAssets(
      context,
      maxAssets: 9,
      selectedAssets: imagesAssetList,
      requestType: sourceType,
    );
    if (asset.length > 0) {
      state.commentsList[index]['image'] = asset;
      setState(() {});
    }
    if (asset.length == 0) return;
    String imageUrl = '';
    upImageClick(
      imagesAssetList: asset,
      upIndex: 0,
      imageUrl: imageUrl,
      chooseIndex: index,
    );
  }

  // 上传图片
  void upImageClick({
    List<AssetEntity> imagesAssetList,
    int upIndex,
    String imageUrl,
    int chooseIndex,
  }) async {
    int uIndex = 0;
    String vStr = state.commentsList[chooseIndex]['list_video'];
    String iStr = state.commentsList[chooseIndex]['imageUrl'];

    /// 获取之前上传的视频和图片的长度
    if (vStr.isNotEmpty || iStr.isNotEmpty) {
      int l1 = 0;
      int l2 = 0;
      if (vStr.isNotEmpty) {
        l1 = vStr.split(",").length;
      }
      if (iStr.isNotEmpty) {
        l2 = iStr.split(",").length;
      }
      uIndex = l1 + l2;
    }
    EasyLoading.show(
      status: "${uIndex + 1}/${imagesAssetList.length} ",
      maskType: EasyLoadingMaskType.black,
    );
    print('====----=-==--=--=-=-=图片上传 ===$vStr ==$iStr');

    print("====----=-==--=--=-=-=图片上传  upIndex===$uIndex");

    AssetEntity upAsset = imagesAssetList[uIndex];
    File file = await upAsset.originFile;
    File compressedFile;
    Map<String, dynamic> parm = {};
    if (upAsset.type == AssetType.video) {
      var info = await VideoCompress.compressVideo(
        file.path,
        quality: VideoQuality.LowQuality, // default(100)
      );
      compressedFile = info.file;
    } else {
      compressedFile = await FlutterNativeImage.compressImage(
        file.path,
        quality: 100,
        percentage: 40,
      );
    }
    List<int> imageData = await compressedFile.readAsBytes();
    print('================ upAsset.name = ${upAsset.titleAsync}');
    String name = await upAsset.titleAsync;
    MultipartFile multipartFile = MultipartFile.fromBytes(
      imageData,
      filename: name,
    );
    parm['file'] = multipartFile;

    Api.upImage(FormData.fromMap(parm)).listen((event) {
      EasyLoading.dismiss();
      if (event["code"] == 0) {
        // if (imageUrl == '') {
        //   imageUrl = event["result"][0]["url"];
        // } else {
        //   imageUrl = imageUrl + ',${event["result"][0]["url"]}';
        // }
        String url = event["result"][0]["url"];
        if (upAsset.type == AssetType.video) {
          if (vStr.isEmpty) {
            state.commentsList[chooseIndex]['list_video'] = url;
          } else {
            List<String> l = vStr.split(",");
            l.add(url);
            state.commentsList[chooseIndex]['list_video'] = l.join(",");
          }
        } else {
          // state.commentsList[chooseIndex]['imageUrl'] = imageUrl;
          if (iStr.isEmpty) {
            state.commentsList[chooseIndex]['imageUrl'] = url;
          } else {
            List<String> l = iStr.split(",");
            l.add(url);
            state.commentsList[chooseIndex]['imageUrl'] = l.join(",");
          }
        }
        logic.update();
        print('====----=-==--=--=-=-=图片上传 链接 imageUrl = $url ');

        if ((imagesAssetList.length) > uIndex + 1) {
          upImageClick(
            imagesAssetList: imagesAssetList,
            upIndex: upIndex + 1,
            imageUrl: imageUrl,
            chooseIndex: chooseIndex,
          );
        } /*else {
          if (upAsset.type == AssetType.video) {
            state.commentsList[chooseIndex]['list_video'] = imageUrl;
          } else {
            state.commentsList[chooseIndex]['imageUrl'] = imageUrl;
          }

          logic.update();
        }*/
      }
    }, onError: (error) {
      print(' 图片上传失败 error = $error');
    });
  }
}
